﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTeachSoft.CoreObjects;
using System.Xml.Serialization;
using System.IO;
using iTeachSoft.Code.Utility;

namespace iTeachSoft.Code.PersistenceLayer
{
    class PersistenceLayer
    {
        /// <summary>
        /// Loads a project from HDD.
        /// </summary>
        /// <param name="filePath"> the path to the project file </param>
        /// <returns></returns>
        public static Project LoadProject(string filePath)
        {
            if (!System.IO.File.Exists(filePath)) return null;
            Project result = null;
            XmlSerializer serializer = new XmlSerializer(typeof(Project));
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open);
                result = (Project)serializer.Deserialize(file);
            }
            catch (Exception ex)
            {
                AlertUtility.ShowError(ex.Message);
                return null;
            }

            return result;
        }

        /// <summary>
        /// Save a project to HDD (as a ZIP archive).
        /// </summary>
        /// <param name="filePath">Path on HDD where the file will be saved.</param>
        /// <param name="project">Project to be saved.</param>
        public static void SaveProject(string filePath, Project project)
        {
            if (project == null) return;
            XmlSerializer serializer = new XmlSerializer(typeof(Project));

            FileStream file = new FileStream(filePath, FileMode.Create);
            if (file == null) return;
            serializer.Serialize(file, project);
            file.Close();

            //TODO copy all files, make a zip archive and save it on the disk
        }
    }
}
